<template>
  <page title="角色管理">
    <el-container>
      <el-header>
        <h1 class="title">角色列表</h1>
        <el-popover
            trigger="click"
            width="170px"
            v-model:visible="visible">
          <template #reference>
            <i class="el-icon-circle-plus add-button"></i>
          </template>
          <el-form>
            <el-form-item label="角色名:">
              <el-input size="mini" v-model="charaName"></el-input>
            </el-form-item>
          </el-form>
          <div style="text-align: right;margin-top: 10px">
            <el-button size="mini" type="text" @click="visible = false">取消</el-button>
            <el-button type="primary" size="mini" @click="addCharacter">确定</el-button>
          </div>
        </el-popover>
        <h1 style="display: inline-block;margin-left: 100px">角色权限</h1>
      </el-header>
      <el-container>
        <el-aside width="200px">
          <el-scrollbar height="500px">
            <el-menu default-active = 0 @select="handleMenuChange">
              <el-menu-item v-for="(c,index) in characters" :key="c.id" :index="index.toString()">
                <div class="menu">
                  {{c.name}}（{{c.userCount}}）
                  <template v-if="activate === index.toString()">
                    <div class="edit-button">
                      <i class="el-icon-edit" @click="handleEdit(c.id,c.name)"></i>
                      <i class="el-icon-delete" @click="handleDelete(c.id)"></i>
                    </div>
                  </template>
                </div>
              </el-menu-item>
            </el-menu>
          </el-scrollbar>
        </el-aside>
        <el-main style="padding:0">
          <div style="width: 50%;padding: 0 10% 0 10%">
            <el-scrollbar height="500px">
              <el-tree
                  :data="data"
                  :props="defaultProps"
                  show-checkbox
                  default-expand-all
                  check-on-click-node
                  :expand-on-click-node="false"
                  node-key="id"
                  ref="tree"
                  @check="handleNodeChange"></el-tree>
            </el-scrollbar>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </page>
</template>

<script>
import Page from "@/components/Page";
import axios from "axios";
export default {
  name: "CharaManage",
  components: {Page},
  data(){
    return{
      visible:false,
      charaName:'',
      characters:[],
      activate:0,
      data: [],
      defaultProps: {
        children: 'subMenu',
        label: 'name'
      }
    }
  },
  methods:{
    addCharacter(){
      this.insertCharacter({id:0,name:this.charaName})
      console.log(this.charaName);
      this.visible = false;
      this.charaName = '';
    },
    handleMenuChange(index,indexPath,item){
      console.log(index,indexPath,item);
      this.activate = index;
      console.log(this.activate);
      this.updateCheck();
    },
    handleNodeChange(node,status){
      console.log(node,status)
      var authCode = 0;
      status.checkedNodes.forEach((element)=>{
        if(element.authCode != null){
          authCode |= element.authCode;
        }
      })
      this.updateCharacterAuth(this.characters[this.activate].id,authCode).then(()=>{
        this.findAllCharacter();
        // this.getMenu();
      }).catch((error)=>{
        if (error.response) {
          console.log(error.response.status)
          switch (error.response.status) {
            case 401:
              this.$router.push("/login");
              break;
            case 403:
              this.$message.error("权限不足");
          }
        }else{
          this.$message.error("网络异常");
        }
        this.getMenu();
      });
    },
    checkNode(ids){
      this.$refs.tree.setCheckedKeys(ids);
    },
    handleEdit(id,name){
      return  this.$prompt('新名称', '重命名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: name
      }).then(({ value }) => {
        this.updateCharacter({id:id,name:value})
      });
    },
    handleDelete(id){
      return  this.$confirm('确认删除此角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          this.deleteCharacterById(id);
      });
    },
    findAllCharacter(){
      return  axios.get(this.$host+"/character").then(response =>{
        if(response.data.code === 0){
          this.characters = response.data.data;
        }else{
          this.$message.error(response.data.msg);
        }
      })
    },
    insertCharacter(data){
      return  axios.post(this.$host+"/character",data).then(response =>{
        if(response.data.code === 0){
          this.$message.success("添加成功");
          this.findAllCharacter();
        }else{
          this.$message.error(response.data.msg);
        }
      })
    },
    updateCharacter(data){
      return  axios.put(this.$host+"/character",data).then(response =>{
        if(response.data.code === 0){
          this.$message.success("修改成功");
          this.findAllCharacter();
        }else{
          this.$message.error(response.data.msg);
        }
      })
    },
    deleteCharacterById(id){
      return  axios.delete(this.$host+"/character/"+id).then(response =>{
        if(response.data.code === 0){
          this.$message.success("删除成功");
          this.findAllCharacter();
        }else{
          this.$message.error(response.data.msg);
        }
      })
    },
    updateCharacterAuth(characterId,authCode){
      return axios.post(this.$host+"/character/auth",null,{
        params:{
          characterId:characterId,
          authCode:authCode
        }
      })
    },
    getMenu(){
      return axios.get(this.$host+"/common/menu").then(response =>{
        if(response.data.code === 0){
          this.data = response.data.data;
        }else{
          this.$message.error(response.data.msg);
        }
      })
    },
    updateCheck(){
      var checkedNode = [];
      this.recur(this.data,this.characters[this.activate],checkedNode);
      this.checkNode(checkedNode);
    },
    recur(menu,curCharacter,checkedNode){
      menu.forEach((element)=>{
        if((element.authCode & curCharacter.authCode) !== 0){
          checkedNode.push(element.id);
        }
        if(element.subMenu.length > 0){
          this.recur(element.subMenu,curCharacter,checkedNode);
        }
      },this);
    }
  },
  created() {
    Promise.all([this.findAllCharacter(), this.getMenu()]).then(()=>{
      this.updateCheck();
    });
  }
}
</script>

<style scoped>
.title{
  margin-right: 90px;
  display: inline-block
}
.add-button{
  font-size: 24px;
  color: rgb(16, 71, 247);
  cursor: pointer;
}
.menu{
  width: 100%;
  height: 100%;
  position: relative;
}
.edit-button{
  display: inline-block;
  position: absolute;
  right: 0;
}
</style>